﻿using Comm520;
using RFIDSystem.DAL;
using RFIDSystem.DAL.Common;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace RFIDSystem
{
    public partial class CheckStock : BaseForm
    {
        DLC520Socket dlcsocket;

        List<stock_check> checks;
        public CheckStock()
        {
            InitializeComponent();
            dlcsocket = this.GetSocket(SocketPort);
            dlcsocket.DataReceived += new DLC520Socket.MachineDataReceived(DataReceived);
        }


        bool DataReceived(string data)
        {
            try
            {

                //datetime=20160507163510,ip=192.168.1.10,result=15,event=1,cardx4=54585382,mdno=487,redio=0,photono=32,
                string cardid = "", ip = "", datetime = "", occur = "", result = "", before = "", after = "", mdno = "", cdno = "", dealtype = "", macno = "", serno = "", status = "";
                string[] items = data.Split(',');
                for (int index = 0; index < items.Length; index++)
                {
                    if (items[index].IndexOf("cardid", 0) >= 0 || items[index].IndexOf("cardx4", 0) >= 0)
                    {
                        cardid = items[index].Substring(7);
                    }
                    if (items[index].IndexOf("ip", 0) >= 0)
                    {
                        ip = items[index].Substring(3);
                    }
                    if (items[index].IndexOf("datetime", 0) >= 0)
                    {
                        datetime = items[index].Substring(9);
                    }
                    if (items[index].IndexOf("occur", 0) >= 0)
                    {
                        occur = items[index].Substring(6);
                    }
                    if (items[index].IndexOf("result", 0) >= 0)
                    {
                        result = items[index].Substring(7);
                    }
                    if (items[index].IndexOf("before", 0) >= 0)
                    {
                        before = items[index].Substring(7);
                    }
                    if (items[index].IndexOf("after", 0) >= 0)
                    {
                        after = items[index].Substring(6);
                    }
                    if (items[index].IndexOf("mdno", 0) >= 0)
                    {
                        mdno = items[index].Substring(5);
                    }
                    if (items[index].IndexOf("cdno", 0) >= 0)
                    {
                        cdno = items[index].Substring(5);
                    }
                    if (items[index].IndexOf("dealtype", 0) >= 0)
                    {
                        dealtype = items[index].Substring(9);
                    }
                    if (items[index].IndexOf("status", 0) >= 0)
                    {
                        status = items[index].Substring(7);
                    }
                    if (items[index].IndexOf("macno", 0) >= 0)
                    {
                        macno = items[index].Substring(6);
                    }
                    if (items[index].IndexOf("serno", 0) >= 0)
                    {
                        serno = items[index].Substring(6);
                    }

                }
                //AddProductInList(cardid);
                this.Invoke(new Action<TextBox, string>((t, s) => t.Text = s), new object[] { txtProductRFID, cardid });
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        private void txtProductRFID_TextChanged(object sender, EventArgs e)
        {
            if (txtProductRFID.Text == "")
                return;

            AddProductInList(txtProductRFID.Text);
            txtProductRFID.Text = "";
            BindList();
        }

        private void CheckStock_Load(object sender, EventArgs e)
        {
            checks = new List<stock_check>();
            gridProductList.AutoGenerateColumns = false;
            BindCheckStockList();
        }

        private void AddProductInList(string rfid)
        {
            var product = DAL.product_product.FirstOrDefault(p => p.product_rfid == rfid);

            if (product == null)
            {
                return;
            }

            

            stock_check checkItem;
            var query = from o in checks
                        where o.product_product.product_id == product.product_id
                        select o;


            if (query.FirstOrDefault() == null)
            {
                int maxId = 0;
                if (checks != null && checks.Count > 0)
                {
                    maxId = (from o in checks
                             select o.check_id).Max();
                }

                int? inQty = (from a in product.stock_in
                              select a.qty_in).Sum();
                int? outQty = (from b in product.sale_order
                               select b.sale_qty).Sum();
                string local = product.stock_in.ToList()[0].local;

                checkItem = new stock_check()
                {

                    check_id = maxId + 1,
                    product_product = product,
                    check_product_name = product.product_name,
                    check_product_model = product.product_model,
                    sys_qty = inQty - outQty,
                    local= local,
                    real_qry = 1
                };

                checks.Add(checkItem);
            }
            else
            {
                checkItem = query.FirstOrDefault();
                checkItem.real_qry++;                
            }
        }

        private void BindList()
        {
            var query = from c in checks
                        select c;

            List<stock_check> checkList = query.ToList();

            this.gridProductList.DataSource = checkList;
        }

        private void BindCheckStockList()
        {
            lbList.Items.Clear();
            var query = (
                            from c in DAL.stock_check                      
                            group c by new { c.check_code, c.check_datetime } into temp
                            orderby temp.Key.check_code descending
                            select new { temp.Key.check_code, temp.Key.check_datetime, count = temp.Count() }
                            
                        ).ToList();

            for(int i=0;i<query.Count();i++)
            {
                string temp = string.Format("{0}|{1}", query[i].check_code, query[i].check_datetime);
                lbList.Items.Add(temp);
            }
            
        }

        private void gridProductList_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (gridProductList.Rows.Count > 0 && e.RowIndex >= 0)
            {
                string columnName = gridProductList.Rows[e.RowIndex].Cells[e.ColumnIndex].OwningColumn.Name;
                if (columnName == "real_qry")
                {
                    foreach (DataGridViewRow r in this.gridProductList.Rows)
                    {
                        int id = (int)r.Cells["check_id"].Value;

                        var check = checks.Find(c => c.check_id == id);
                        check.real_qry = (int)r.Cells["real_qry"].Value;                      

                    }
                    BindList();
                }
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (this.checks == null || this.checks.Count == 0)
            {
                MessageBox.Show("盘点清册为空，不需保存");
                return;
            }

            string orderCode = "C" + DateTime.Now.ToString("yyyyMMddhhmmss");
            DateTime time = DateTime.Now;

            foreach (stock_check c in checks)
            {
                c.check_code = orderCode;
                c.check_datetime = time;

            }

            DAL.stock_check.AddRange(checks);
            DAL.SaveChanges();

            MessageBox.Show("保存成功!");
            this.checks.Clear();
            BindList();
            BindCheckStockList();
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            if (lbList.SelectedItem == null)
            {
                MessageBox.Show("先选择一条需要打印的盘点记录");
                return;
            }

            var printForm = new CheckStockPrint();
            printForm.CheckCode = lbList.SelectedItem.ToString().Split('|')[0];
            printForm.CheckTime = lbList.SelectedItem.ToString().Split('|')[1];
            printForm.Show();
        }
    }
}
